package com.yh.test;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: Liang
 * @Date: 2024/5/13 - 05 - 13 - 9:24
 * @Description: com.yh.test
 * @version: 1.0
 */

public class MyDataSource {

    //C3P0连接池
     @Test
     public void c3() throws PropertyVetoException, SQLException {
         //创建数据源
         ComboPooledDataSource dataSource = new ComboPooledDataSource();
         //设置数据库连接参数
         dataSource.setDriverClass("com.mysql.jdbc.Driver");
         dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
         dataSource.setUser("root");
         dataSource.setPassword("123456");
         //获得连接对象
         Connection connection = dataSource.getConnection();
         System.out.println(connection);
         //关闭连接池
         dataSource.close();
     }

     //Druid连接池
    @Test
    public void druidTest() throws SQLException {
        //创建数据源
        DruidDataSource dataSource = new DruidDataSource();
        //设置数据库连接参数
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        //获得连接对象
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        //关闭连接池
        dataSource.close();
    }

    @Test
    public  void springC3p0Test() throws SQLException {
        //1.加载配置文件创建spring容器
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("spring.xml");
        //2.指定对象并使用
        DataSource c3p0 = (DataSource) applicationContext.getBean("c3p0");
        Connection connection = c3p0.getConnection();
    }

    @Test
    public void springDruidTest() throws PropertyVetoException, SQLException {
        //1.加载配置文件创建spring容器
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("spring.xml");
        //2.指定对象并使用
        DataSource druid = (DataSource) applicationContext.getBean("druid");
        Connection connection = druid.getConnection();
    }
}
